import requests
import re
from LSTM.variableset import EMVar
import pandas as pd
from emmobileapi import sys_strategy_fund as sysStrategyFund


def dfcf():

    r = requests.get('http://nufm2.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=0000011,3990062,3990012&'
                     'sty=DFPIU&st=z&sr=&p=&ps=&cb=&token=44c9d251add88e27b65ed86506f6e5da&0.9562427171040326')
    if r.status_code == requests.codes.ok:
        # 代码， 名称， 当前指数， 成交量， 涨跌点， 百分比， 上证涨|平|跌|?, 深圳涨|平|跌|?
        # '0000011,上证指数,3388.25,178552877056,7.55,0.22%,416|138|873|81,538|218|1355|172'
        result = r.text.replace('[\"', '').replace('(', '').replace('\"]', '').replace(')', '').replace(',\"',':').replace('\"', '').\
            replace('0000011', '000001').replace('3990062', '399006').replace('3990012', '399001').replace('|', ',')
        result = result.split(':')
        l = []
        for i in result:
            i = i.split(',')
            if len(i) == 14:
                if i[0] == EMVar.CODE_SH:
                    d = {'code': i[0], 'name': i[1], 'price': i[2], 'volume': i[3], 'szs': float(i[6]), 'pjs': float(i[7]),
                         'xds': float(i[8])}
                    l.append(d)
                elif i[0] == EMVar.CODE_SZ:
                    d = {'code': i[0], 'name': i[1], 'price': i[2], 'volume': i[3], 'szs': float(i[10]), 'pjs': float(i[11]),
                         'xds': float(i[12])}
                    l.append(d)
        df = pd.DataFrame(l)
        df['sz_pct'] = df['szs']/(df['szs']+df['xds'])
        df['xd_pct'] = 1 - df['sz_pct']
        return df


def yimeng_position():
    r = requests.get('http://hq.emoney.cn/')
    if r.status_code == requests.codes.ok:
        if r.encoding == 'ISO-8859-1':
            encodings = requests.utils.get_encodings_from_content(r.text)
            if encodings:
                encoding = encodings[0]
            else:
                encoding = r.apparent_encoding

            # encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace')
            encode_content = r.content.decode(encoding, 'replace')  # 如果设置为replace，则会用?取代非法字符；
        else:
            raise Exception('编码检测异常')
        l = re.compile('<span class="red font35 font_arial">(.*)%</span></div><div class="weather_scjd_content2">').findall(
            encode_content)
        pct = float(l[0])/100 if len(l) else 0
        return pct
    return 0

def zdf():
    df1, t1 = sysStrategyFund.req_strategy_fund(key='今日涨幅大于3%,上市大于100', max_count=200, sleep=0)
    df2, t2 = sysStrategyFund.req_strategy_fund(key='今日跌幅小于-3%,上市大于100', max_count=200, sleep=0)
    df3, t3 = sysStrategyFund.req_strategy_fund(key='今日涨停,上市大于100', max_count=200, sleep=0)
    df4, t4 = sysStrategyFund.req_strategy_fund(key='今日跌停,上市大于100', max_count=200, sleep=0)
    # M:minus P:plus
    return {'ZD_P3': t1, 'ZD_M3': t2, 'ZD_P10': t3, 'ZD_M10': t4}

# dfcf()

# yimeng_position()

# zdf()